class AccountController < ApplicationController
  def new
    @user = current_user
    @categories = Category.all
    if (@user.id == nil)
      redirect_to login_url
    end
     @hot_books = Book.search_hot_book()    
  end

  def show
    @categories = Category.all
    @books = Book.search(params[:search])
  end

  def create
    @user = current_user
    @book = Book.find(params[:book_id])
    @path = params[:path]
    begin
      if (@user.borrow_items.count == 5)
        redirect_to @path, :notice => 'You can borrow maximum 5 books'
      return
      else
        if (@book.numbers == @book.numbers_to_borrow)
          redirect_to @path, :notice => 'Can not borrow this book'
        else
          if (@user.borrow_items.find(params[:book_id]) != nil)
            redirect_to @path, :notice => 'Can not borrow the book which had been borrowed'
          return
          else
            @book_item = @user.borrow_items.build(:book => @book)
            if (@book_item.save)
              @book.numbers_to_borrow += 1
              @book.save
              @category_item = CategoryItem.where(:user_id => @user.id, :category_id => @book.category.id)
              if (@category_item.exists?)
                @category_item = CategoryItem.search(@user.id, @book.category.id)
                @category_item.number += 1
                @category_item.save
              end
              redirect_to viewbooks_index_path(:book_id => @book), :notice => 'You have borrowed'
            else
              redirect_to @path, :notice => 'Can not borrow this book'
            end
          end
        end
      end

    rescue
      @book_item = @user.borrow_items.build(:book => @book)
      if (@book_item.save)
        @book.numbers_to_borrow += 1
        if (@book.save)
          @category_item = CategoryItem.where(:user_id => @user.id, :category_id => @book.category.id)
          if (@category_item.exists?)
            @category_item  = @user.category_items.find(@book.category.id)
          @category_item.number += 1;
          else
            @category_item = @user.category_items.build(:category => @book.category)
          @category_item.number = 1
          end
          @category_item.save
          redirect_to viewbooks_index_path(:book_id => @book), :notice => 'You have borrowed'
        else
          redirect_to @path, :notice => 'Can not borrow this book'
        end
      else
        redirect_to @path, :notice => 'Can not borrow this book'
      end
    end
  end

end
